package com.runner.track;

import java.util.ArrayList;
import java.util.Iterator;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.runner.utility.Constants;

public class CloudManager implements Constants {

	public static final float MIN_TIME = 2;
	public static final float MAX_TIME = 5;
	public static final float OPACITY = 0.7f;

	private ArrayList<Cloud> clouds;
	private float timer;
	private float time;
	private String path;
	private float height;
	private float scale;
	private float speed;

	public CloudManager(float speed) {
		path=RINGER_CLOUD_PATH;
		this.speed=speed;
		clouds = new ArrayList<Cloud>();
		generateNewCloud();
		timer = time/2;
	}

	

	private void pickCloudAttributes() {
		height = MathUtils.random(0.65f, 0.88f);
		scale = MathUtils.random(0.7f, 1.3f);
	}

	public void generateNewCloud() {
		pickCloudAttributes();
		clouds.add(new Cloud(new Vector2(VIRTUAL_WIDTH, VIRTUAL_HEIGHT * height), path, scale, speed));
		time = MathUtils.random(MIN_TIME, MAX_TIME);
	}

	public void update(float delta) {
		timer += delta;
		// generate clouds at random time
		if (timer >= time) {
			generateNewCloud();
			timer = 0;
		}
		// update clouds
		for (Iterator<Cloud> i = clouds.iterator(); i.hasNext();) {
			Cloud c = i.next();
			c.update(delta);
			if (!c.isExists()) {
				i.remove();
			}
		}
	}

	public void render(SpriteBatch sb) {
		for (Cloud c : clouds) {
			c.render(sb, OPACITY);
		}
	}

	public void reset() {
		clouds.clear();
		generateNewCloud();
	}
	
	public void generatePresetClouds() {
		int num=MathUtils.random(2, 4);
		float deviation=1/(float)num;
		for(int i=0; i<num; i++){
			pickCloudAttributes();
			float pos=MathUtils.random(i*deviation, (i*deviation)+deviation);
			clouds.add(new Cloud(new Vector2(VIRTUAL_WIDTH*pos,VIRTUAL_HEIGHT * height), path, scale, speed));
		}
		
	}

	public void loadClouds(PLAYER_TYPE pType) {
		switch (pType) {
		case RINGER:
			path = RINGER_CLOUD_PATH;
			break;
		case APRIL:
			path = APRIL_CLOUD_PATH;
			break;
		case GEO:
			path = GEO_CLOUD_PATH;
			break;
		}
		generatePresetClouds();
	}
}
